<template>
    <!--  搜索框组件-->
      <TableSearch  :deletSome="deletSomes"  @deletSome="deletSomeUsers"  :search-fields="searchFields"  @search="handleSearch"  @reset="handleReset"></TableSearch>
      <!-- 表格组件 -->
      <TableComponent
          :columns="columns"
          :tableData="tableData"
          :loading="loading"
          :deletSome="deletSomes"
          @delete="handleDelete"
          @somedelete="handleSomeDelete"
      />
      <pagination  :current-page="currentPage"  :page-size="pageSize"  :total="total"   @size-change="handleSizeChange"
     @current-change="handleCurrentChange"></pagination>
    </template>
    <script setup>
    import { ref, reactive, onMounted } from 'vue';
    
    import  pagination from '@/components/pagination/index.vue';
    import TableSearch from '@/components/TableSearch/teachersearch.vue';
    import TableComponent from '@/components/DataTable/logtable.vue';
    
    import api from '@/api/log'
    import router from "@/router/index.js";
    import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
    
    // 侧边栏折叠状态
    const sidebarCollapsed = ref(false);
    
    let deletSomes= true;
    // 搜索字段
    const searchFields = reactive([
      { label: '登录用户', prop: 'loginName', type: 'input' },
      { label: '权限', prop: 'role', type: 'select', options: [
      { label: '超级管理员', value: '超级管理员' },
      { label: '讲师', value: '讲师'},
    ]},
      // { label: '登录时间', prop: 'loginTime', type: 'date-range' },
    ]);
    
    // 表格列定义
    const columns = [
        { prop: 'id', label: '序号', width: 80,headerAlign: 'center'},
        { prop: 'loginName', label: '姓名', width: 120 ,headerAlign: 'center'},
        { prop: 'role', label: '权限', width: 120 ,headerAlign: 'center'},
        { prop: 'loginIp', label: '登录ip', width: 180 ,headerAlign: 'center'},
        { prop: 'loginTime', label: '登录时间', width: 300 ,headerAlign: 'center'},
        { prop: 'backTime', label: '退出时间', width: 300 ,headerAlign: 'center'},
    ];
    
    // 表格数据
    const tableData = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    let users;
    const Search =ref({})
    // 加载表格数据
    const loadData = async () => {
      loading.value = true;
    
      try {
        Search.value.pageNum = currentPage.value;
        Search.value.pageSize = pageSize.value;
    
        // const response = await api.selectAll(Search.value);
        const response = await api.selectAllT(Search.value);
        console.log("日志列表"+response.data);
    
        tableData.value = response.data.list || [];
        total.value = response.data.total || 0;
        console.log('加载数据成功:', response);
        if (response.code == 200) {
          // 开发环境调试日志
        } else {
          // API返回了错误码
          throw new Error(response.message || '获取数据失败');
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        // 友好的错误提示
        ElMessage.error({
          message: error.message || '加载数据失败，请稍后重试',
          duration: 3000
        });
    
        // 重置数据防止显示旧数据
        tableData.value = [];
        total.value = 0;
      } finally {
        loading.value = false;
      }
    };
    function addUser() {
      router.push(`/teacher/create`);
    }
    // 批量删除
    async function deletSomeUsers() {
      try {
        // 确认对话框
        const confirmResult = await ElMessageBox.confirm(
            '确定要批量删除这些用户吗？此操作不可撤销！',
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );
    
        if (confirmResult !== 'confirm') {
          return; // 用户点击了取消
        }
    
        // 极速模式：所有删除请求同时发起
        const loadingInstance = ElLoading.service({
          lock: true,
          text: '正在批量删除用户...',
          background: 'rgba(0, 0, 0, 0.7)'
        });
    
        const results = await Promise.allSettled(
            Object.values(users).map(tLog =>
                api.deletUser({ id: tLog.id })
                    .then(() => ({ status: 'fulfilled',  id: tLog.id }))
                    .catch(error => ({ status: 'rejected',  id: tLog.id, error }))
            )
        );
    
        // 关闭加载动画
        loadingInstance.close();
    
        // 生成统计报告
        const successCount = results.filter(r => r.status === 'fulfilled').length;
        const failedCount = results.filter(r => r.status === 'rejected').length;
    
        // 刷新数据
        await loadData();
    
        // 显示操作结果
        if (failedCount === 0) {
          ElMessage.success(`成功删除 ${successCount} 个用户`);
        } else if (successCount === 0) {
          ElMessage.error(`删除失败，所有 ${failedCount} 个用户均未删除成功`);
        } else {
          ElMessage.warning(
              `删除完成，成功 ${successCount} 个，失败 ${failedCount} 个`,
              { duration: 5000 }
          );
        }
    
        return {
          total: results.length,
          success: successCount,
          failed: failedCount,
          errors: results.filter(r => r.status === 'rejected').map(r => ({
            userId: r.userId,
            error: r.error.message
          }))
        };
    
      } catch (error) {
        // 用户可能点击了取消按钮，不需要处理
        if (error !== 'cancel' && error !== 'close') {
          ElMessage.error(`删除操作出错: ${error.message}`);
        }
        return null;
      }
    }
    
    function editUserRow(row) {
      router.push(`/teacher/${row.userId}/edit`);
      // sessionStorage.setItem("user",JSON);
    }
    // 处理搜索
    const handleSearch = (params) => {
      console.log('Search params:', params);
      currentPage.value = 1;
      Search.value = params;
      loadData();
    };
    
    // 处理重置
    const handleReset = () => {
      Search.value = {};
      currentPage.value = 1;
      loadData();
    };
    
    // 删除功能
    const handleDelete = async (row) => {
      // 极速模式：所有删除请求同时发起
      try {
        await ElMessageBox.confirm(
            `确定要删除数据 "${row.loginName}" (ID: ${row.id}) 吗？`,
            '删除确认',
            {
              confirmButtonText: '确认删除',
              cancelButtonText: '取消',
              type: 'warning',
              closeOnClickModal: false, // 防止误点
              beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                  instance.confirmButtonLoading = true;
                  try {
                    const loadingInstance = ElLoading.service({
                      lock: true,
                      text: '正在删除用户...',
                      background: 'rgba(0, 0, 0, 0.7)'
                    });
    
                    await api.deletUser({ id: row.id });
                    done();
                    // 关闭加载动画
                    loadingInstance.close();
                  } catch (error) {
                    instance.confirmButtonLoading = false;
                    // 关闭加载动画
                    loadingInstance.close();
                    throw error;
                  }
                } else {
                  done();
                }
              }
            }
        );
    
        // 删除成功后刷新数据
        await loadData();
    
        ElMessage({
          type: 'success',
          message: `用户 "${row.userName}" 删除成功`,
          duration: 3000
        });
    
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage({
            type: 'error',
            message: `删除失败: ${error.message || '未知错误'}`,
            duration: 5000
          });
        } else {
          ElMessage({
            type: 'info',
            message: '已取消删除操作',
            duration: 2000
          });
        }
      }
    };
    function handleSomeDelete(rows) {
       users=rows;
       console.log(rows,"获取多列的值")
    }
    // 处理每页数量变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      loadData();
    };
    
    // 处理页码变化
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
      loadData();
    };
    function deleteclick() {
    
    }
    // 初始化加载数据
    onMounted(() => {
      loadData();
    });
    </script>
    
    <style scoped>
    #app {
      font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
      min-height: 100vh;
    }
    </style>